<?php

namespace app\company\controller;

use app\common\controller\CompanyController;
use app\common\exception\BaseException;
use app\Request;
use think\App;
use think\db\exception\DbException;
use think\response\Json;
use app\company\model\Feedback as FeedBackModel;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;

/**
 * @ControllerAnnotation(title="意见反馈")
 */
class Feedback extends CompanyController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new FeedBackModel();
    }

    /**
     * @NodeAnnotation(title="意见反馈列表")
     * @throws DbException
     */
    public function index(): Json
    {
        $keyword = $this->request->get('keyword');
        $startTime = $this->request->get('start_time');
        $endTime = $this->request->get('end_time');
        $limit = $this->request->get('limit', 15);

        $where = [];
        if ($keyword) {
            $where[] = ['content', 'like', "%{$keyword}%"];
        }

        $feedbacks = $this->model->where($where)
            ->when($startTime && $endTime, function ($query) use ($startTime, $endTime) {
            $query->whereBetweenTime('time', $startTime, $endTime);
        })->order('time', 'desc')->paginate($limit);

        return $this->success($feedbacks);
    }

    /**
     * @NodeAnnotation(title="意见反馈添加")
     *
     * @param Request $request
     * @return Json
     * @throws BaseException
     */
    public function create(Request $request): Json
    {
        $this->checkPost();
        $post = $this->request->post();
        $rule = [
            'content|内容' => 'require',
        ];
        $this->validate($post, $rule);
        $post['time'] = date("Y-m-d H:i:s", time());
        $post['name'] = $this->userInfo['username'];

        try {
            $this->model->save($post);

            return $this->success();
        } catch (\Exception $e) {
            // 捕获异常并返回错误信息
            return $this->error('系统错误：' . $e->getMessage());
        }
    }
}
